package hgx.spring.cloud.lession.zk;/**
 * Created by liujun on 2018/6/17.
 */



import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.List;

/**
 * @author hugx
 * @create 2018-06-17 12:27
 */
public class MyDataMointor implements AsyncCallback.StatCallback {
    private ZooKeeper zk;
    private String node;
    private MyDataListener myDataListener;
    private List<String> nodes;

    public MyDataMointor(ZooKeeper zk,String node,MyDataListener myDataListener) {
        this.zk=zk;
        this.node=node;
        this.myDataListener=myDataListener;
//        zk.exists(node,true,  this,null);
    }

    interface  MyDataListener{
        void close();
    }


    public void process(WatchedEvent event) {
       switch (event.getState()){
           case Expired:
               System.out.println("*** process() of MyDataMointor is  Expired");
               myDataListener.close();
               break;
           case Disconnected:
               break;
           case SyncConnected:
               zk.exists(node,true,this,null);
               if(nodes !=null && !nodes.isEmpty()){
                   for(String nodeTmp : nodes){
                       zk.exists(nodeTmp,true,this,null);
                   }
               }
               break;
               default:
       }
    }


    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        try {

            byte [] bytes=zk.getData(node,false,null);
            System.out.println("**** processResult() of MyDataMointor  path: "+path+" , bytes: "+(bytes !=null ? new String(bytes):""));
            this.nodes= zk.getChildren(node,true);
           if(this.nodes !=null && !this.nodes.isEmpty()){
               StringBuilder sb=new StringBuilder("**** processResult() of MyDataMointor  data: ");
               for(String str : this.nodes){
                   byte [] data2=zk.getData(node+"/"+str,false,null);
                   sb.append("key: ").append(node).append("/").append(str).append("  value: ").append((data2 !=null ? new String(data2): "")).append(" ,");
               }
               sb.deleteCharAt(sb.lastIndexOf(","));
               System.out.println(sb.toString());
           }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
